package com.xwc.cloud.support.loadbalancer.gateway;


import com.xwc.cloud.support.loadbalancer.LoadbalancerSupportProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * 类描述：添加请求头到请求信息中
 * 作者：徐卫超 (cc)
 * 时间 2022/5/12 16:34
 */
public class RouterIpHeaderWriteGlobalFilter implements GlobalFilter, Ordered {
    private ReactiveExtractTargetRouter reactiveExtractTargetRouter;
    private LoadbalancerSupportProperties loadbalancerSupportProperties;

    public RouterIpHeaderWriteGlobalFilter(ReactiveExtractTargetRouter reactiveExtractTargetRouter,
                                           LoadbalancerSupportProperties loadbalancerSupportProperties) {
        this.reactiveExtractTargetRouter = reactiveExtractTargetRouter;
        this.loadbalancerSupportProperties = loadbalancerSupportProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String ip = this.reactiveExtractTargetRouter.get(exchange);
        // 查看请求中有没有目标IP
        if (StringUtils.hasText(ip) &&
                !exchange.getRequest().getHeaders().containsKey(loadbalancerSupportProperties.getIpRule().getRouterAttrName())) {
            // 把路由信息放入到请求头中
            Consumer<HttpHeaders> httpHandlerConsumer = httpHeaders -> {
                httpHeaders.set(loadbalancerSupportProperties.getIpRule().getRouterAttrName(), ip);
            };
            ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHandlerConsumer).build();
            ServerWebExchange serverWebExchange = exchange.mutate().request(request).build();
            return chain.filter(serverWebExchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
